package cn.iocoder.yudao.module.shop.category.service;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.framework.thirdparty.zxhx.ZXHXApiClientFactory;
import cn.iocoder.yudao.framework.thirdparty.zxhx.dto.ZXHXCategoryItemRespDTO;
import cn.iocoder.yudao.module.api.shop.category.eums.ShopCategoryCodeEnum;
import cn.iocoder.yudao.module.shop.category.dao.ShopCategoryMapper;
import cn.iocoder.yudao.module.shop.category.pojo.po.ShopCategory;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.module.api.supply.ConfigConstants.SUPPLY_NAME_ZXHX;
import static cn.iocoder.yudao.module.shop.category.pojo.po.ShopCategory.PARENT_ID_ROOT;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 *  这里是文件说明
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/03/04
 */
@Service
@Validated
@Slf4j
public class ZXHXShopCategorySyncServiceImpl implements ZXHXShopCategorySyncService {

    @Resource
    private ShopCategoryMapper shopCategoryMapper;

    @Override
    public int autoSync() {
        ShopCategory mallCategory = shopCategoryMapper.selectByCode(ShopCategoryCodeEnum.MALL.getCode());
        Assertions.notNull(mallCategory, "顶级行业类目【" + ShopCategoryCodeEnum.MALL.getName() + "】不存在");
        List<ZXHXCategoryItemRespDTO> allCategory = ZXHXApiClientFactory.productClient().getAllCategory();
        if (CollUtil.isEmpty(allCategory)) {
            return 0;
        }
        int count = 0;
        List<ShopCategory> categoryExists = shopCategoryMapper.selectBySupplyRelatedIds(allCategory.stream().map(ZXHXCategoryItemRespDTO::getId).collect(Collectors.toSet()));
        List<ShopCategory> insertList = new ArrayList<>();
        for (ZXHXCategoryItemRespDTO itemRespDTO : allCategory) {
            if (categoryExists.stream().anyMatch(categoryDO -> itemRespDTO.getId().equals(categoryDO.getSupplyRelatedId()))) {
                continue;
            }
            ShopCategory shopCategory = new ShopCategory();
            shopCategory.setParentId(0L);
            shopCategory.setName(itemRespDTO.getName());
            shopCategory.setIconUrl("");
            shopCategory.setLinkUrl("#");
            shopCategory.setSort(itemRespDTO.getId().intValue());
            shopCategory.setDepth(1);
            shopCategory.setStatus(CommonStatusEnum.ENABLE.getStatus());
            shopCategory.setSupplyName(SUPPLY_NAME_ZXHX);
            shopCategory.setSupplyRelatedId(itemRespDTO.getId());
            shopCategory.setSupplyRelatedParentId(itemRespDTO.getParentId());
            insertList.add(shopCategory);
        }
        log.info("插入行业类目数据：{} 条", insertList.size());
        shopCategoryMapper.insertBatch(insertList);
        count += insertList.size();
        List<ShopCategory> categoryAll = shopCategoryMapper.selectList();
        List<ShopCategory> updateList = toCategoryDOS(categoryAll, mallCategory);
        log.info("更新行业类目父级编号：{} 条", updateList.size());
        shopCategoryMapper.updateById(updateList);
        return count;
    }

    @Nonnull
    private List<ShopCategory> toCategoryDOS(List<ShopCategory> categoryAll, ShopCategory mallCategory) {
        List<ShopCategory> list = new ArrayList<>();
        for (ShopCategory category : categoryAll) {
            if (!SUPPLY_NAME_ZXHX.equals(category.getSupplyName())) {
                continue;
            }
            if (Objects.equals(category.getSupplyRelatedParentId(), PARENT_ID_ROOT)) {
                ShopCategory shopCategory = new ShopCategory();
                shopCategory.setId(category.getId());
                shopCategory.setParentId(mallCategory.getId());
                list.add(shopCategory);
                continue;
            }
            for (ShopCategory it : categoryAll) {
                if (Objects.equals(category.getSupplyRelatedParentId(), it.getSupplyRelatedId())) {
                    ShopCategory shopCategory = new ShopCategory();
                    shopCategory.setId(category.getId());
                    shopCategory.setParentId(it.getId());
                    list.add(shopCategory);
                    break;
                }
            }
        }
        return list;
    }

}
